import type { FC } from 'react';
import { useMemo } from 'react';
import { useSafeState, useMemoizedFn } from 'ahooks';
import { Input, Button, Row, Col, Modal } from 'antd';
import MapControl from './mapControl';
import type { PoiItem } from './mapControl/types';

export type Address = {
  province: string;
  city: string;
  district: string;
  street: string;
  longitude: number;
  latitude: number;
}

type MapSelectProps = {
  value?: Address;
  onChange?: (value: Address) => void;
}

const MapSelect: FC<MapSelectProps> = (props) => {
  const { value } = props;

  const [
    openMap,
    setOpenMap
  ] = useSafeState(false);

  const handleOpenMap = useMemoizedFn(
    () => setOpenMap(true)
  );

  const handleCloseMap = useMemoizedFn(
    () => setOpenMap(false)
  );

  const showAddress = useMemo(() => {
    if (!value) return;

    return [
      value.province,
      value.city,
      value.district,
      value.street
    ].join('');
  }, [value])

  const handleOk = useMemoizedFn((poi: PoiItem) => {
    const address = {
      province: poi.pname,
      city: poi.cityname,
      district: poi.adname,
      street: poi.address,
      latitude: poi.location.lat,
      longitude: poi.location.lng,
    }
    handleCloseMap();
    props.onChange?.(address);
  })

  return (
    <Row gutter={16}>
      <Col flex={1}>
        <Input
          readOnly
          value={showAddress}
          placeholder="请选择场馆位置"
        />
      </Col>
      <Col flex="none">
        <Button
          type="primary"
          onClick={handleOpenMap}
        >
          选择位置
        </Button>
      </Col>
      <Modal
        centered
        width="99vw"
        title="请选择"
        open={openMap}
        destroyOnClose
        footer={null}
        onCancel={handleCloseMap}
        children={(
          <MapControl
            onOk={handleOk}
            defaultValue={value}
          />
        )}
      />
    </Row>
  );
}

export default MapSelect;